"use strict";
import './style.scss'
class Controller {
    constructor (systemService, $state, $stateParams, uiNotification, localStorageService) {
        "ngInject"
        this.notify           = uiNotification;
        this.stateParam       = $stateParams;
        this.breadcrumb       = localStorageService.get('corp.path');
        this.type             = $state.current.url.match(/post|user|staff|role|corp/)[ 0 ];
        this.tempSelect       = [];
        // 已授权
        this.checkedGrantList = [];
        // 缓存 table tree 数据
        this.cache            = {};
        this.treeNode         = [];
        // 权限菜单操作
        this.addMenuList      = [];
        this.delMenuList      = [];
        this.checkedMenuList  = [];
        // 权限组件操作
        this.addCompList      = [];
        this.delCompList      = [];
        this.checkedCompList  = [];
        this.current          = {
            page    : $stateParams.orgName,
            type    : (this.type == 'post' ? '岗位' : this.type == 'role' ? '角色' : '用户'),
            typeName: $stateParams.cur
        };
        this.treeData         = {
            parMenuId   : 0,
            grantObjType: $state.current.data.grantType,
            grantObjId  : $stateParams.core
        };

        this.compData = {
            grantObjType: $state.current.data.grantType,
            sysCode     : this.sysCode,
            grantObjId  : $stateParams.core,
            menuId      : ''
        };

        this.privMenuAddData = {
            grantObjType: $state.current.data.grantType,
            operType    : 'ADD',
            grantObjId  : $stateParams.core
        };

        this.privMenuDelData = {};

        this.privCompAddData = {
            grantObjType: $state.current.data.grantType,
            operType    : 'ADD',
            grantObjId  : $stateParams.core
        };

        this.privCompDelData = {};

        this.service = systemService;

        // 获取归属平台列表
        systemService.getPlat().then(res => {
            this.platList = res.data;
        });

    }

    getTree (force) {
        if ( force ) {
            angular.extend(this.treeData, {
                sysCode  : this.select.platSysNbr,
                parMenuId: 0
            })
        } else {
            if ( this.isLoad ) return;
            this.isLoad = true;
        }
        this.service.getTree('menuComp', this.treeData).then((res) => {
            __DEBUG__ && console.log(res.data)
            if ( force ) {
                this.cache           = {};
                this.checkedMenuList = [];
                this.checkedCompList = [];
                this.treeNode        = res.data;
                this.notify.success({
                    'title'  : '提示',
                    'message': '操作成功!'
                });
            } else {
                this.cache[ this.treeData.parMenuId ] = res.data;
                this.treeNode                         = this.cache[ this.treeData.parMenuId ];
            }
            for (let i = 0, l = res.data.length; i < l; i++) {
                let temp = res.data[ i ];
                if ( temp.hadPriv ) {
                    this[ temp.compId ? 'checkedCompList' : 'checkedMenuList' ].push({
                        privId     : temp.privId,
                        privGrantId: temp.privGrantId
                    })
                }
            }
            __DEBUG__ && console.log(this.checkedCompList)
            __DEBUG__ && console.log(this.checkedMenuList)
        }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        }).finally(() => {
            this.isLoad = false;
        })

    }

    onSelected (item) {
        this.select          = item;
        this.cache           = {};
        this.treeNode        = [];
        // 权限菜单操作
        this.addMenuList     = [];
        this.delMenuList     = [];
        this.checkedMenuList = [];
        // 权限组件操作
        this.addCompList     = [];
        this.delCompList     = [];
        this.checkedCompList = [];
        angular.extend(this.treeData, {
            sysCode  : item.platSysNbr,
            parMenuId: 0
        })
        this.getTree()
    }

    /**
     * 子元素权限交互展示
     * @param childNodes
     * @param type
     */
    toggleChild (childNodes, type) {
        let n, idx;
        _.forEach(childNodes, (v) => {
            n = v.compId ? { privId  : v.privId, compName: v.compName} : { privId: v.privId, menuName: v.menuName}
            if (!v.privGrantId) {
                idx = _.findIndex(this[v.compId ? 'addCompList': 'addMenuList'], {privId: v.privId})
                if (type == 'add') {
                    if (idx === -1) {
                        this[v.compId ? 'addCompList': 'addMenuList'].push(n)
                    }
                }
                if (type == 'del') {
                    this[v.compId ? 'addCompList': 'addMenuList'].splice(idx,1)
                }
            } else {
                idx = _.findIndex(this[v.compId ? 'delCompList': 'delMenuList'], {privId: v.privId})
                if (type == 'add') {
                    this[v.compId ? 'delCompList': 'delMenuList'].splice(idx,1)
                }
                if (type == 'del') {
                    if (idx === -1) {
                        this[ v.compId ? 'delCompList' : 'delMenuList' ].push(n)
                    }
                }
            }
        })
    }

    toggleCheck (type, scope, node) {
        let isCheck = (node.hadPriv = !node.hadPriv);
        let parent     = scope.$nodeScope.$parentNodeScope;
        let pChildCount = parent && parent.childNodesCount()
        let childCount = scope.$nodeScope.childNodesCount();
        let childNodes = scope.$nodeScope.$modelValue.nodes;
        if (parent && !childCount) {
            if (!isCheck) {
                let idx = _.findIndex(this.tempSelect, node.id)
                this.tempSelect.splice(idx, 1)
            } else {
                this.tempSelect.push(node.id)
                this.tempSelect = _.uniq(this.tempSelect)
            }
            parent.$modelValue.checkAll = pChildCount === this.tempSelect.length ? true : false
        }
        if ( type == 'menu' ) {
            // 去掉选中为子节点时,同步父节点
            if ( childCount ) {
                _.map(childNodes, (item) => {
                    return item.hadPriv = isCheck
                })
            }
            let ifMenuExist = _.findIndex(this.checkedMenuList, {privId: node.privId}) > -1 ? true : false;
            if ( isCheck ) {
                if ( ifMenuExist ) {
                    if ( node.privGrantId ) {
                        let delIdx = _.findIndex(this.delMenuList, {
                            privId: node.privId
                        });
                        (delIdx > -1) && this.delMenuList.splice(delIdx, 1);
                    }
                } else {
                    let addIdx = _.findIndex(this.addMenuList, {privId: node.privId});
                    (addIdx == -1) && this.addMenuList.push({
                        privId  : node.privId,
                        menuName: node.menuName
                    })
                }
                if (childCount) {
                    this.toggleChild(childNodes, 'add')
                    node.checkAll = true;
                }
            } else {
                if ( !node.privGrantId ) {
                    let addIdx = _.findIndex(this.addMenuList, {
                        privId: node.privId
                    });
                    (addIdx > -1) && this.addMenuList.splice(addIdx, 1);
                }
                if ( ifMenuExist ) {
                    if ( node.privGrantId ) {
                        this.delMenuList.push({
                            privId     : node.privId,
                            privGrantId: node.privGrantId,
                            menuName   : node.menuName
                        })
                    }
                    if (childCount) {
                        this.toggleChild(childNodes, 'del')
                    }
                }
            }
        }

        if ( type == 'comp' ) {
            let ifCompExist = (_.findIndex(this.checkedCompList, {privId: node.privId}) > -1) ? true : false;
            if ( isCheck ) {
                if ( ifCompExist ) {
                    if ( node.privGrantId ) {
                        let delIdx = _.findIndex(this.delCompList, {
                            privId: node.privId
                        });
                        (delIdx > -1) && this.delCompList.splice(delIdx, 1);
                    }
                } else {
                    let addIdx = _.findIndex(this.addCompList, {privId: node.privId});
                    (addIdx == -1) && this.addCompList.push({
                        privId  : node.privId,
                        compName: node.compName
                    })
                }
            } else {
                if ( !node.privGrantId ) {
                    let addIdx = _.findIndex(this.addCompList, {
                        privId: node.privId
                    });
                    (addIdx > -1) && this.addCompList.splice(addIdx, 1);
                }
                if ( ifCompExist ) {
                    if ( node.privGrantId ) {
                        this.delCompList.push({
                            privId     : node.privId,
                            privGrantId: node.privGrantId,
                            compName   : node.compName
                        })
                    }
                }
            }
        }
    }

    toggleNode (scope, node, $event) {
        $event.preventDefault();
        if ( !node.hasChildren && !node.hadComp ) return false;
        /*this.currentNode = node.menuName;
         this.parMenuId   = node.menuId;*/
        if ( scope.collapsed ) {
            scope.expand();
            if ( node.hasChildren || node.hadComp ) {
                if ( this.cache[ node.menuId ] ) {
                    node.nodes = this.cache[ node.menuId ];
                    return;
                }
                node.loading            = true;
                this.treeData.parMenuId = node.menuId;
                this.service.getTree('menuComp', this.treeData).then((res)=> {
                    this.cache[ node.menuId ] = res.data;
                    node.nodes                = this.cache[ node.menuId ];
                    let exist;
                    for (let i = 0, l = res.data.length; i < l; i++) {
                        let temp = res.data[ i ];
                        if ( temp.hadPriv == true ) {
                            exist = _.findIndex(this[ temp.compId ? 'checkedCompList' : 'checkedCompList' ], {privId: res.data[ i ].privId}) > -1 ? true : false;
                            if ( !exist ) {
                                this[ temp.compId ? 'checkedCompList' : 'checkedMenuList' ].push({
                                    privId     : res.data[ i ].privId,
                                    privGrantId: res.data[ i ].privGrantId
                                });
                            }
                        }
                    }
                }).catch((data) => {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                }).finally(function () {
                    node.loading = false;
                });
            }
        } else {
            scope.collapse();
        }
    }

    serialize (list, attr) {
        let r = [];
        _.forEach(list, function (v) {
            r.push(v[ attr ])
        })
        return r.join(',');
    }

    save (type) {
        if ( type == 'menu' ) {
            //批量增加菜单
            if ( this.addMenuList.length ) {
                this.privMenuAddData.ids = this.serialize(this.addMenuList, 'privId');
                this.service.insert('batchPriv', this.privMenuAddData).then((res)=> {
                    angular.forEach(res.data, (v) => {
                        this.checkedMenuList.push({
                            privId     : v.privId,
                            privGrantId: v.privGrantId
                        })
                    })
                    this.addMenuList = [];
                }).then(() => {
                    this.getTree(1)
                }).catch((data) => {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                }).finally(function () {
                });
            }

            // 批量删除菜单
            if ( this.delMenuList.length ) {
                this.privMenuDelData.ids = this.serialize(this.delMenuList, 'privGrantId');
                this.service.delItem('batchPriv', this.privMenuDelData).then(()=> {
                    let temp = this.privMenuDelData.ids.split(',');
                    angular.forEach(temp, (v) => {
                        let idx = _.indexOf(this.checkedMenuList, v)
                        this.checkedMenuList.splice(idx, 1)
                    })
                    this.delMenuList = [];
                }).then(() => {
                    this.getTree(1)
                }).catch((data) => {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                })
            }
        }

        if ( type == 'comp' ) {
            // 批量增加组件
            if ( this.addCompList.length ) {
                this.privCompAddData.ids = this.serialize(this.addCompList, 'privId');
                this.service.insert('batchPriv', this.privCompAddData).then((res)=> {
                    angular.forEach(res.data, (v) => {
                        this.checkedCompList.push({
                            privId     : v.privId,
                            privGrantId: v.privGrantId
                        })
                    })
                    this.addCompList = [];
                }).then(() => {
                    this.getTree(1)
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }
            // 批量删除组件
            if ( this.delCompList.length ) {
                this.privCompDelData.ids = this.serialize(this.delCompList, 'privGrantId');
                this.service.delItem('batchPriv', this.privCompDelData).then(()=> {
                    let temp = this.privCompDelData.ids.split(',');
                    angular.forEach(temp, (v) => {
                        let idx = _.indexOf(this.checkedCompList, v)
                        this.checkedCompList.splice(idx, 1)
                    })
                    this.delCompList = [];
                }).then(() => {
                    this.getTree(1)
                }).catch(function (data) {
                    this.notify.error({
                        'title'  : '提示',
                        'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                    });
                });
            }
        }
    }
}

export default Controller;